<?php

declare(strict_types=1);

namespace Service\WebSocketService;

use Service\BaseService;
use Service\Code\Normal;
use Service\ExportService\ExportExcelHandle;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use App\Model\BbcModel\GoodsManagerTags;
use App\Model\BbcModel\GoodsBrand;
use App\Model\BbcModel\Goodscommon;
use App\Model\BbcModel\DistributorPrice;
use App\Model\BbcModel\DistributorLevel;
use App\Model\BbcModel\GoodsTags;
use Service\CommodityService\ChannelCommodityCommonService;

/**
 * 渠道商品导出-前置仓商品导出
 * @author chenshubo
 */
class ChannelCommoditySpService extends BaseService {
    /**
     * 前置仓商品导出
     * @param object $server
     * @param int $fd
     * @param array $body
     * @param int $manager_id
     * @param int $cid
     * 推送前端客户端方式
     * Normal::returnCode(Normal::WS_START,"开始处理");
     * Normal::returnCode(Normal::WS_END,"处理完成");
     * Normal::returnCode(Normal::WS_ERROR,"处理异常");
     * $server->push($fd,json_encode($result,JSON_UNESCAPED_UNICODE));
     */
    public function spGoodsExport($server, int $fd, array $body, int $manager_id, int $cid) {
        $param        = $body;
        $param['sp']  = 1;
        $param['cid'] = $cid;
        $whereRaw     = ChannelCommodityCommonService::instance()->handleWhere($param);
        $sortRaw      = ChannelCommodityCommonService::instance()->handleSort($param);
        $fields       = [
            'id', 'name', 'class_id', 'high_price', 'tax_free', 'tax_free_cloud', 'is_high_goods', 'high_tax_rate', 'brand_id', 'status',
            'num_storage', 'origin', 'is_bonded', 'price_cost', 'price_market', 'price_recommend', 'skucode', 'barcode', 'tax_rate',
            'price_recommend_vip', 'weight', 'price_store', 'isfree_postfee', 'tag', 'supply_tag', 'type', 'manager_tag'
        ];
        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 20,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }
        $list = Goods::select($fields)->where('is_trade', 0)->whereRaw($whereRaw)->orderByRaw($sortRaw)->get()->toArray();
        if (!$list) {
            return Normal::returnCode(Normal::WS_ERROR, '无数据可导出');
        }
        $distributor_level          = DistributorLevel::where('cid', $cid)->orderBy('id', 'asc')->select(['level', 'name'])->get()->toArray();
        $distributor_level_index    = array_column($distributor_level, 'name', 'level');
        $class_ids                  = array_column($list, 'class_id');
        $classIndex                 = GoodsClass::whereIn('id', $class_ids)->pluck('name', 'id')->toArray();
        $classPid                   = GoodsClass::whereIn('pid', $class_ids)->pluck('name', 'pid')->toArray();
        $brand_ids                  = array_column($list, 'brand_id');
        $brandIndex                 = GoodsBrand::whereIn('id', $brand_ids)->pluck('name', 'id')->toArray();
        $supplyTagArr               = GoodsTags::where('cid', $cid)->pluck('show_name', 'id')->toArray();
        $managerTagArr              = GoodsManagerTags::where('cid', $cid)->pluck('name', 'id')->toArray();
        $goods_ids                  = array_column($list, 'id');
        $distributor_level_pric_arr = DistributorPrice::where('cid', $cid)->whereIn('goods_id', $goods_ids)->select(['goods_id', 'price', 'level_id'])->get();
        $exportData                 = [];
        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 40,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }
        foreach ($list as $k => $v) {
            $classSecond = $classPid[$v['class_id']] ?? '无分类';
            //是否包邮
            $isfree_postfee = $v['isfree_postfee'] == 1 ? '是' : '否';
            //标签
            $manager_tag_ids = explode(',', $v['manager_tag']);
            $tag_str         = '';
            if ($manager_tag_ids) {
                $tag_str_arr = [];
                foreach ($manager_tag_ids as $manager_tag_id) {
                    if (isset($managerTagArr[$manager_tag_id])) {
                        $tag_str_arr[] = $managerTagArr[$manager_tag_id];
                    }
                }
                if ($tag_str_arr) {
                    $tag_str = implode(',', $tag_str_arr);
                }
            }
            //供应商标签
            $supply_tag_ids = explode(',', $v['supply_tag']);
            $supply_tag_str = '';
            if ($supply_tag_ids) {
                $supply_tag_str_arr = [];
                foreach ($supply_tag_ids as $supply_tag_id) {
                    if (isset($supplyTagArr[$supply_tag_id])) {
                        $supply_tag_str_arr[] = $supplyTagArr[$supply_tag_id];
                    }
                }
                if ($supply_tag_str_arr) {
                    $supply_tag_str = implode(',', $supply_tag_str_arr);
                }
            }

            if ($v['is_bonded'] == 1 && $v['tax_free'] == 1) {
                if ($v['high_price'] > 0) {
                    $pricestoretax_rate = $v['tax_rate'];
                    $pricecosttax_rate  = $v['tax_rate'];
                    if ($v['price_store'] >= $v['high_price']) {
                        $pricestoretax_rate = $v['high_tax_rate'];
                    }
                    if ($v['price_cost'] >= $v['high_price']) {
                        $pricecosttax_rate = $v['high_tax_rate'];
                    }
                    $except_money = round(($v['price_store'] / (1 + $pricestoretax_rate) - $v['price_cost'] / (1 + $pricecosttax_rate)), 2);
                } else {
                    $except_money = round(($v['price_store'] / (1 + $v['tax_rate']) - $v['price_cost'] / (1 + $v['tax_rate'])), 2);
                }
            } else {
                $except_money = round(($v['price_store'] - $v['price_cost']), 2);
            }
            $is_high_goods                = $v['is_high_goods'] > 0 ? '是' : '否';
            $taxfree                      = $v['tax_free_cloud'] > 0 ? '是' : '否';
            $exportData[$k]               = [
                $v['id'], $v['name'], $classSecond, $classIndex[$v['class_id']] ?? '无分类', $v['class_id'] ?? 0, $brandIndex[$v['brand_id']] ?? '无品牌', $v['brand_id'] ?? 0,
                Goodscommon::$is_bonded[$v['is_bonded']] ?? '',
                Goods::$status[$v['status']] ?? '', $v['skucode'], $v['barcode'], $v['tax_rate'], $v['price_cost'], $v['price_store'], $v['price_recommend'],
                $v['price_market'], $v['price_recommend_vip'], $v['num_storage'], $v['origin'], $v['weight'] / 1000, $except_money, $is_high_goods, $taxfree, $v['high_price']
            ];
            $exportData[$k][]             = $isfree_postfee;
            $exportData[$k][]             = $supply_tag_str; //供应商标签
            $exportData[$k][]             = $tag_str; //后台标签
            $exportData[$k][]             = Goods::$settlementType[$v['type']] ?? '未定义'; //定价方式
            $distributor_level_pric_index = $distributor_level_pric_arr->where('goods_id', $v['id'])->pluck('price', 'level_id')->toArray();
            foreach ($distributor_level_index as $key => $val) {
                if (array_key_exists($key, $distributor_level_pric_index)) { //设置了等级分销商结算价
                    $exportData[$k][] = $distributor_level_pric_index[$key];
                } else {
                    $exportData[$k][] = $v['price_store'];
                }
            }
        }
        if ($server) {
            $send = Normal::returnCode(Normal::WS_START, "进行中", [
                'percent' => 90,
            ]);
            $server->push($fd, json_encode($send, JSON_UNESCAPED_UNICODE));
        }
        $data['header'] = [
            'id', '商品名称', '一级分类', '二级分类', '分类id', '品牌', '品牌id', '商品类型', '状态', 'SKU', '国际条码', '税率', '成本价', '下游结算价',
            '建议零售价', '市场价', '推荐会员价', '库存', '产地', '重量(kg)', '预估利润', '是否触发消费税', '云仓商品价格是否含税', '含税预警价',
            '供应商是否包邮', '供应商标签', '商品标签', '定价方式'
        ];
        foreach ($distributor_level_index as $v) {
            $data['header'][] = $v;
        }
        $data['data']     = $exportData;
        $data['fileName'] = '前置仓商品资料.xlsx';
        $exportRes        = ExportExcelHandle::instance()->uploadAliOssSource($data['fileName'], $data['header'], $data['data']);
        if ($exportRes['code'] != Normal::SUC) {
            return Normal::returnCode(Normal::WS_ERROR, $exportRes['msg'] ?? '导出失败');
        }
        return Normal::returnCode(Normal::WS_END, "已完成", [
            'percent'      => 100.00,
            'download_url' => $exportRes['data']['path'],
        ]);
    }
}